package com.dms.modules.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.modules.community.entity.CommunityTag;
import com.dms.modules.community.mapper.CommunityTagMapper;
import com.dms.modules.community.service.CommunityTagService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CommunityTagServiceImpl extends ServiceImpl<CommunityTagMapper, CommunityTag> implements CommunityTagService {

    @Override
    public List<CommunityTag> getAvailableTags() {
        return this.list(new LambdaQueryWrapper<CommunityTag>()
                .eq(CommunityTag::getStatus, 1)
                .orderByDesc(CommunityTag::getUseCount));
    }

    @Override
    public List<CommunityTag> getHotTags(Integer limit) {
        return this.list(new LambdaQueryWrapper<CommunityTag>()
                .eq(CommunityTag::getStatus, 1)
                .orderByDesc(CommunityTag::getUseCount)
                .last("LIMIT " + limit));
    }

    @Override
    @Transactional
    public void incrementUseCount(Long tagId) {
        CommunityTag tag = this.getById(tagId);
        if (tag != null) {
            tag.setUseCount(tag.getUseCount() + 1);
            this.updateById(tag);
        }
    }

    @Override
    @Transactional
    public void decrementUseCount(Long tagId) {
        CommunityTag tag = this.getById(tagId);
        if (tag != null && tag.getUseCount() > 0) {
            tag.setUseCount(tag.getUseCount() - 1);
            this.updateById(tag);
        }
    }
}